<template>
  <div
    class="ScaleBox"
    ref="ScaleBox"
    :style="{
      width: width + 'px',
      height: height + 'px',
    }"
  >
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: "ScaleBox",
  props: {
    baseOnWidth: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      scaleX: 1,
      scaleY: 1,
      width: 1920,
      height: 1080,
    };
  },
  mounted() {
    this.setScale();
    window.addEventListener("resize", this.debounce(this.setScale));
  },
  methods: {
    getScale() {
      const { width, height } = this;
      const wh = window.innerHeight / height;
      const ww = window.innerWidth / width;
      // 返回宽度和高度的缩放比例
      return { scaleX: ww, scaleY: wh };
    },
    setScale() {
      const { scaleX, scaleY } = this.getScale();
      this.scaleX = scaleX;
      this.scaleY = scaleY;
      if (this.$refs.ScaleBox) {
        this.$refs.ScaleBox.style.setProperty("--scaleX", this.scaleX);
        this.$refs.ScaleBox.style.setProperty("--scaleY", this.scaleY);
      }
    },
    debounce(fn, delay = 500) {
      let timer;
      return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => fn.apply(this, args), delay);
      };
    },
  },
};
</script>
<style lang="scss" scoped>
#ScaleBox {
  --scaleX: 1;
  --scaleY: 1;
}
.ScaleBox {
  position: absolute;
  transform: scale(var(--scaleX), var(--scaleY)) translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  transform-origin: 0 0;
  left: 50%;
  top: 50%;
  transition: 0.3s;
  z-index: 999;
}
</style>
